#coding=utf-8
import os
import sys
import datetime
import logging.handlers
from enum import Enum

from qturboframe.lib.common.__const__ import LOG_FILE


class LogLevel(Enum):
    '''
    日志级别
    '''
    DEBUG = 0
    INFO = 1
    WARN = 2
    ERROR = 3


class LocalLogger(object):
    """
    本地日志

    :Attributes:
     - log_level: 日志级别，包括debug、info、warn、error四个级别；默认使用debug级别
    """
    def __init__(self, log_level=0):
        # 创建handler，用于输出控制台日志
        self.control_handler = logging.StreamHandler()
        self.file_full_name = LOG_FILE
        if not os.path.exists(os.path.dirname(self.file_full_name)):
            os.makedirs(os.path.dirname(self.file_full_name))
        self.file_handler = logging.FileHandler(self.file_full_name)
        self.logger = None
        self.levels = {LogLevel.DEBUG.value : logging.DEBUG,
                       LogLevel.INFO.value : logging.INFO,
                       LogLevel.WARN.value : logging.WARN,
                       LogLevel.ERROR.value : logging.ERROR,
                       'debug': logging.DEBUG,
                       'info': logging.INFO,
                       'warn': logging.WARN,
                       'error': logging.ERROR}
        self.log_level = log_level
        self.log_max_byte = 10 * 1024 * 1024
        self.log_backup_count = 10

    def get_logger(self):
        '''记录日志，规范日志格式'''
        if self.logger is not None:
            return self.logger
        self.logger = logging.Logger("Log.Logger")
        # 日志格式化
        logging.Formatter.default_msec_format = '%s.%03d'
        log_control_fmt = logging.Formatter("%(asctime)s [%(levelname)s] -> <%(funcName)s><%(filename)s>:%(message)s")
        # log_control_fmt = logging.Formatter("%(asctime)s [%(levelname)s] --> %(message)s")
        self.control_handler.setFormatter(log_control_fmt)
        self.file_handler.setFormatter(log_control_fmt)
        self.logger.addHandler(self.control_handler)
        self.logger.addHandler(self.file_handler)
        self.logger.setLevel(self.levels.get(self.log_level))
        return self.logger


# 日志对象
# Example: logger.info('打印日志。')
local_logger = LocalLogger().get_logger()


if __name__ == '__main__':
    local_logger.info("test")